<template>
  <div class="dashboard-container">
    <div class="three-column-layout">
      <!-- 第一列：上下2个模块 -->
      <div class="column column-first">
        <!-- 第一列上面模块：行业数据浏览与下载 -->
        <div class="dashboard-module" style="margin-top: 20px;padding: 20px 20px 0 20px;">
          <div class="module-header">行业数据浏览与下载</div>
          <div class="module-content">
            <!-- 政策标准浏览小模块 -->
            <div class="sub-module">
              <div class="sub-module-header">政策标准浏览</div>
              <div class="sub-module-content">
                <PolicyViewChart ref="policyViewChart" chartId="main-1" />
              </div>
            </div>

            <!-- 政策标准下载量小模块 -->
            <div class="sub-module">
              <div class="sub-module-header">政策标准下载量</div>
              <div class="sub-module-content">
                <PolicyDownloadChart ref="policyDownloadChart" chartId="main-2" />
              </div>
            </div>
          </div>
        </div>

        <!-- 第一列下面模块：企业投诉 -->
        <div class="dashboard-module">
          <div class="module-header">企业投诉</div>
          <div class="module-content">
            <EnterpriseComplaintChart ref="enterpriseComplaintChart" chartId="enterpriseComplaintChart" />
            <!-- <img src="../assets/img/bingbgc.png" alt="" class="rotunditybox"> -->
          </div>
        </div>
      </div>

      <!-- 第二列：2个模块，上面模块是下面模块的2/3 -->
      <div class="column column-second">
        <!-- 第二列上面模块：政策与标准 -->
        <div class="dashboard-module module-large" style="margin-top: 20px;padding: 20px 20px 0 20px;">
          <div class="module-header">政策与标准</div>
          <div class="module-content">
            <div class="stats-grid">
              <!-- <div class="stat-card" v-for="(card, index) in cards" :key="index">
                <div class="stat-title">{{ card.title }}</div>
                <div class="stat-value">{{ card.value }}{{ card.title.includes('下降率') ? '%' : '' }}</div>
              </div> -->
              <div class="stat-card" @click="handleClick(hangye)">
                <div class="stat-title">行业</div>
                <div class="stat-value">{{ cardsList.hY }}</div>
              </div>
              <div class="stat-card" @click="handleClick(gjStandard)">
                <div class="stat-title">颁布国标</div>
                <div class="stat-value">{{ cardsList.gjStandard }}</div>
              </div>
              <div class="stat-card" @click="handleClick(hyStandard)">
                <div class="stat-title">颁布行标</div>
                <div class="stat-value">{{ cardsList.hyStandard }}</div>
              </div>
              <div class="stat-card" @click="handleClick(fenlei)">
                <div class="stat-title">分类</div>
                <div class="stat-value">{{ cardsList.fL }}</div>
              </div>
              <div class="stat-card">
                <div class="stat-title">国标投诉下降率</div>
                <div class="stat-value">50%</div>
              </div>
              <div class="stat-card">
                <div class="stat-title">行标投诉下降率</div>
                <div class="stat-value">30%</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 第二列下面模块：发布标准 -->
        <div class="dashboard-module module-small">
          <div class="module-header">发布标准</div>
          <div class="table-container" v-if="!isStandardsLoading">
            <div class="table-row" v-for="(item, index) in tableData" :key="index">
              <div class="table-cell time">{{ item.time }}</div>
              <div class="table-cell category" :title="item.categories">{{ item.category }}</div>
              <div class="table-cell type">{{ item.type }}</div>
              <div class="table-cell standard">{{ item.standard }}</div>
            </div>

          </div>
          <!-- Loading加载状态 -->
          <div v-else class="loading-container">
            <div class="loading-spinner"></div>
            <span class="loading-text">加载中...</span>
          </div>
        </div>
      </div>

      <!-- 第三列：跟第一列布局一样 -->
      <div class="column column-third">
        <!-- 第三列上面模块：行业数据浏览与下载 -->
        <div class="dashboard-module" style="margin-top: 20px;padding: 20px 20px 0 20px;">
          <div class="module-header">产品浏览对比与结果</div>
          <div class="module-content">
            <!-- 政策标准浏览小模块 -->
            <div class="sub-module">
              <div class="sub-module-header">产品浏览量</div>
              <div class="sub-module-content">
                <ProductBrowseChart ref="productBrowseChart" chartId="productBrowseChart" />
              </div>
            </div>

            <!-- 产品对比次数小模块 -->
            <div class="sub-module">
              <div class="sub-module-header">产品对比次数</div>
              <div class="sub-module-content">
                <ProductCompareChart ref="productCompareChart" chartId="productCompareChart" />
              </div>
            </div>
          </div>
        </div>

        <!-- 第三列下面模块：企业投诉 -->
        <div class="dashboard-module">
          <div class="module-header">产品投诉</div>
          <div class="module-content">
            <ProductComplaintChart ref="productComplaintChart" chartId="productComplaintChart" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import * as echarts from 'echarts'
import { getPolicyBrowseCount, getPolicyDownloadCount, getProductBrowseCount, getProductCompareCount, getComplaintCount, getIndustryStatistics } from '../api/dashboard.js'
import PolicyViewChart from '../components/PolicyViewChart.vue'
import PolicyDownloadChart from '../components/PolicyDownloadChart.vue'
import ProductBrowseChart from '../components/ProductBrowseChart.vue'
import ProductCompareChart from '../components/ProductCompareChart.vue'
import ProductComplaintChart from '../components/ProductComplaintChart.vue'
import EnterpriseComplaintChart from '../components/EnterpriseComplaintChart.vue'
import { getPublishedStandardList } from '../api/user.js'
export default {
  name: 'Dashboard',
  components: {
    PolicyViewChart,
    PolicyDownloadChart,
    ProductBrowseChart,
    ProductCompareChart,
    ProductComplaintChart,
    EnterpriseComplaintChart
  },
  data() {
    return {
      // 保存获取的数据
      browseChartData: null,
      downloadChartData: null,
      productBrowseData: null,
      productCompareData: null,
      complaintData: null,
      cardsList: [],
      hangye: 'industry',
      gjStandard: 'national-standard',
      hyStandard: 'industry-standard',
      fenlei: 'category',
      tableData: [],
      isStandardsLoading: false, // 发布标准模块的loading状态
      scrollTop: 0, // 保存页面滚动位置
    }
  },
  mounted() {
    // 组件挂载后的初始化操作
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize)
    // 禁用页面滚动
    this.disableScroll()
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('resize', this.handleResize)
    // 恢复页面滚动
    this.enableScroll()
  },
  created() {
    // 组件创建时获取数据
    this.fetchPolicyViewData();
    this.fetchPolicyDownloadData();
    this.fetchProductBrowseData();
    this.fetchProductCompareData();
    this.fetchComplaintData();
    this.queryZclist();
    this.QueryStandards();
  },

  methods: {
    // 禁用页面滚动
    disableScroll() {
      // 获取当前滚动位置
      this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0

      // 方法1：设置body样式
      document.body.style.position = 'fixed'
      document.body.style.top = `-${this.scrollTop}px`
      document.body.style.width = '100%'
      document.body.style.overflow = 'hidden'
      document.body.style.height = '100%'
      document.documentElement.style.overflow = 'hidden'
      document.documentElement.style.height = '100%'

      // 方法2：添加事件监听器阻止滚动
      this.handleWheel = (e) => e.preventDefault()
      this.handleTouchMove = (e) => e.preventDefault()
      this.handleKeyDown = (e) => {
        // 阻止方向键和空格键滚动
        if ([32, 33, 34, 35, 36, 37, 38, 39, 40].includes(e.keyCode)) {
          e.preventDefault()
        }
      }

      document.addEventListener('wheel', this.handleWheel, { passive: false })
      document.addEventListener('touchmove', this.handleTouchMove, { passive: false })
      document.addEventListener('keydown', this.handleKeyDown, { passive: false })
    },
    // 恢复页面滚动
    enableScroll() {
      // 移除滚动限制
      document.body.style.position = ''
      document.body.style.top = ''
      document.body.style.width = ''
      document.body.style.overflow = ''
      document.body.style.height = ''
      document.documentElement.style.overflow = ''
      document.documentElement.style.height = ''

      // 移除事件监听器
      document.removeEventListener('wheel', this.handleWheel)
      document.removeEventListener('touchmove', this.handleTouchMove)
      document.removeEventListener('keydown', this.handleKeyDown)

      // 恢复到原来的滚动位置
      window.scrollTo(0, this.scrollTop)
    },
    // 查询发布标准数据
    QueryStandards() {
      this.isStandardsLoading = true; // 开始加载
      getPublishedStandardList().then(res => {
        // 处理API返回的数据并转换为表格所需格式
        if (res.data && Array.isArray(res.data)) {
          this.tableData = res.data.map(item => ({
            time: item.publishDate, // 使用发布日期作为时间
            category: item.baseBusinessIndusty ? item.baseBusinessIndusty[0].name : '', // 只显示第一个行业名称
            categories: item.baseBusinessIndusty ? item.baseBusinessIndusty.map(ind => ind.name).join(', ') : '', // 存储所有行业名称用于悬浮显示
            type: item.standarsPath, // 使用standarsPath替换原来的type
            standard: item.normCode,
            title: item.title
          }));
        }
      }).finally(() => {
        this.isStandardsLoading = false; // 无论成功失败都结束加载
      });
    },
    //首页政策与标准
    queryZclist() {
      getIndustryStatistics().then(res => {
        this.cardsList = res.data;
      });

    },
    //产品企业投诉数据
    async fetchComplaintData() {
      try {
        const response = await getComplaintCount();

        // 保存数据
        this.complaintData = response.data;

        // 更新图表
        this.$nextTick(() => {
          if (this.$refs.productComplaintChart) {
            this.$refs.productComplaintChart.updateChart(response.data.product);
          }
          if (this.$refs.enterpriseComplaintChart) {
            this.$refs.enterpriseComplaintChart.updateChart(response.data.enterprise);
          }
        });
      } catch (error) {
        // console.error("获取投诉数据失败:", error);

        // 为了演示，使用静态数据
        const mockData = {
          product: {
            "价格问题": "1",
            "质量问题": "4",
            "虚假宣传": "2",
            "售后问题": "1"
          },
          enterprise: {
            "质量问题": "2",
            "数据泄露": "4",
            "霸王条款": "2",
            "售后问题": "1"
          }
        };

        this.$nextTick(() => {
          if (this.$refs.productComplaintChart) {
            this.$refs.productComplaintChart.updateChart(mockData.product);
          }
          if (this.$refs.enterpriseComplaintChart) {
            this.$refs.enterpriseComplaintChart.updateChart(mockData.enterprise);
          }
        });
      }
    },

    //首页产品对比次数
    async fetchProductCompareData() {
      try {
        const response = await getProductCompareCount();

        // 保存数据
        this.productCompareData = response.data;

        // 更新图表
        this.$nextTick(() => {
          if (this.$refs.productCompareChart) {
            this.$refs.productCompareChart.updateChart(response.data);
          }
        });
      } catch (error) {
        // console.error("获取产品对比次数数据失败:", error);
      }
    },
    // 获取政策标准浏览量数据并初始化图表
    async fetchPolicyViewData() {
      try {
        const response = await getPolicyBrowseCount();
        // 保存数据
        this.browseChartData = response.data;

        // 更新图表
        this.$nextTick(() => {
          if (this.$refs.policyViewChart) {
            this.$refs.policyViewChart.updateChart(response.data);
          }
        });
      } catch (error) {
        console.error("获取政策标准浏览数据失败:", error);
      }
    },

    // 获取政策标准下载量数据并初始化图表
    async fetchPolicyDownloadData() {
      try {
        const response = await getPolicyDownloadCount();
        // 保存数据
        this.downloadChartData = response.data;
        // 更新图表
        this.$nextTick(() => {
          if (this.$refs.policyDownloadChart) {
            this.$refs.policyDownloadChart.updateChart(response.data);
          }
        });
      } catch (error) {
        console.error("获取政策标准下载数据失败:", error);
      }
    },

    // 获取产品浏览量数据并初始化图表
    async fetchProductBrowseData() {
      try {
        const response = await getProductBrowseCount();
        // 保存数据
        this.productBrowseData = response.data;

        // 更新图表
        this.$nextTick(() => {
          if (this.$refs.productBrowseChart) {
            this.$refs.productBrowseChart.updateChart(response.data);
          }
        });
      } catch (error) {
        console.error("获取产品浏览量数据失败:", error);
      }
    },

    // 处理窗口大小变化
    handleResize() {
      // 每个组件内部已经处理了自己的resize逻辑，这里可以保留作为备用
      console.log('窗口大小变化');
    },
    handleClick(item) {
      if (item === this.hangye) {
        this.$router.push('/userProfile');
      } else if (item === this.gjStandard) {
        this.$router.push('/userManagement');
      } else if (item === this.hyStandard) {
        this.$router.push('/userProfile');
      } else if (item === this.fenlei) {
        this.$router.push('/userProfile');
      }
    }
  }
}
</script>

<style scoped>
/* 使用:deep()选择器修改.main-content样式，使其背景透明 */
:deep(.main-content) {
  background-color: transparent !important;
  background: transparent !important;
}

/* 确保dashboard-container占满整个容器 */
.dashboard-container {
  padding: 20px;
  background-color: transparent;
  /* min-height: 100vh; */
  position: relative;
  overflow: hidden;
  /* 禁止内部滚动 */
  box-sizing: border-box;
  /* 确保padding不会导致溢出 */
  z-index: 1;
  /* 确保容器内容在背景图之上 */
}

/* 修改顶部背景图设置，增强优先级 */
.dashboard-container::before {
  content: '';
  position: fixed;
  top: 60px;
  left: 0;
  width: 100%;
  height: 73px;
  min-height: 73px;
  background-image: url('../assets/img/home/hometopnav.png');
  background-size: auto 93px;
  background-position: top center;
  background-repeat: no-repeat;
  background-color: #011640;
  z-index: 0;
  /* 设置为0，确保在文字内容下方但高于可能的其他背景 */
  pointer-events: none;
  /* 确保不影响鼠标事件 */
}

/* 修改底部背景图设置，增强优先级 */
.dashboard-container::after {
  content: '';
  position: fixed;
  top: calc(60px + 73px);
  left: 0;
  width: 100%;
  height: calc(100vh - 60px - 73px);
  background-image: url('../assets/img/home/homebgc.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-color: #011640;
  z-index: 0;
  /* 设置为0，确保在文字内容下方但高于可能的其他背景 */
  pointer-events: none;
  /* 确保不影响鼠标事件 */
}

/* 其他原有样式保持不变 */
.three-column-layout {
  display: flex;
  gap: 20px;
  height: calc(100vh - 40px);
  /* 减去padding的高度 */
}

.column {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  /* 禁止列内部滚动 */
}

.dashboard-module {
  /* background-color: rgba(2, 18, 48, 0.7);  */
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
  padding: 20px;
  position: relative;
  z-index: 2;
  /* 确保模块内容在最上层 */
}



.module-small {
  flex: 1;
}

.module-header {
  font-size: 20px;
  font-weight: 600;
  height: 48px;
  line-height: 48px;
  margin-bottom: 5px;
  color: #fff;
  background-image: url('../assets/img/home/hometext.png');
  background-size: cover;
  /* background-position: center; */
  border-radius: 4px;
  padding-left: 45px;
  /* 添加左边内边距，让文字右移 */

}



.module-content {
  display: flex;
  flex-direction: column;
}

.sub-module {
  margin-bottom: 15px;
}

.sub-module:last-child {
  margin-bottom: 0;
}

.sub-module-header {
  font-family: Alibaba PuHuiTi, Alibaba PuHuiTi;
  font-weight: 500;
  font-size: 18px;
  /* margin-bottom: 10px; */
  color: #fff;
}

.sub-module-content {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .three-column-layout {
    flex-direction: column;
  }

  .column {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }

  .dashboard-module {
    padding: 15px;
  }
}




.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  width: 100%;
}

/* 统计卡片样式 */
.stat-card {
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

/* 统计标题样式 */
.stat-title {
  font-size: 18px;
  color: #fff;
  margin-bottom: 10px;
  font-weight: 500;
}

@media (max-width: 1980px) and (min-width: 1200px) {
  .stat-title {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    font-weight: 500;
  }
}

/* 统计数值样式 */
.stat-value {
  font-size: 24px;
  font-weight: bold;
  /* 添加背景图片并设置固定大小 */
  background-image: url('../assets/img/home/shuzibgc.png');
  background-size: 100px 60px;
  /* 设置背景图片大小为100px x 60px */
  background-position: center;
  background-repeat: no-repeat;
  /* 调整内边距和文字位置 */
  padding: 5px 15px 15px;
  /* 减少顶部内边距，增加底部内边距让文字上移 */
  height: 60px;
  /* 设置高度与背景图片一致 */
  display: flex;
  align-items: flex-start;
  /* 文字靠上对齐 */
  justify-content: center;
  /* 文字水平居中 */
  border-radius: 4px;
  /* 确保文字清晰可见 */
  color: #fff;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

/* 针对投诉下降率添加特殊样式 */
.stat-card:nth-child(5) .stat-value,
.stat-card:nth-child(6) .stat-value {
  color: #fff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .stat-card {
    padding: 15px;
  }

  .stat-value {
    font-size: 20px;
    background-size: 90px 50px;
    /* 响应式调整背景图片大小 */
    height: 50px;
    padding: 3px 10px 12px;
    /* 响应式调整内边距 */
  }
}


.table-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  /* font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; */
  font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;

}

/* 每一行样式 */
.table-row {
  display: flex;
  align-items: center;
  padding: 12px 8px;
  /* border-bottom: 1px solid #f1f5f9; */
  transition: background-color 0.2s ease;
  cursor: pointer;
}

.table-cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
  line-height: 1.5;
  color: #fff;
}

.category {
  flex: 1;
  color: #fff;
  font-weight: 500;
  position: relative;
  /* cursor: help;  */
}

.type {
  flex: 2;
  color: #fff;
  /* 确保文本超出时显示省略号 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 最后一行不需要底边框 */
.table-row:last-child {
  border-bottom: none;
}

/* 单元格样式 */
.table-cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
  line-height: 1.5;
}

/* 特定列宽度和样式 */
.time {
  flex: 1.5;
  font-size: 13px;
}

.category {
  flex: 1;
  font-weight: 500;
}

.type {
  flex: 2;
  color: #fff;
}

.standard {
  flex: 3;
  color: #fff;
  font-family: 'Consolas', 'Monaco', monospace;
}

/* 鼠标悬停效果 */

/* 响应式设计 */
@media (max-width: 768px) {
  .table-container {
    font-size: 13px;
  }

  .table-row {
    padding: 10px 6px;
  }

  .table-cell {
    font-size: 13px;
  }

  /* 在小屏幕上调整列宽比例 */
  .time,
  .category {
    flex: 1.2;
  }

  .type,
  .standard {
    flex: 2;
  }
}

/* 添加滚动条样式 */
.table-container {
  max-height: 368px;
  /* 限制高度 */
  overflow-y: auto;
}

/* 美化滚动条 */
.table-container::-webkit-scrollbar {
  width: 6px;
}

.table-container::-webkit-scrollbar-track {
  background: transparent;
}

.table-container::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.table-container::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  gap: 10px;
}

/* 加载动画 */
.loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

/* 加载文字 */
.loading-text {
  color: #666;
  font-size: 14px;
}

/* 暂无数据提示 */
.no-data {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  font-size: 14px;
}

/* 旋转动画 */
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>